package org.testtools.runner.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import org.testtools.runner.Runner;

public class ProcessRunner implements Runner {

  private static final char CHAR_LINE_BREAK = '\n';

  public static String runAndGetOutput(String... arg) {
    return runAndGetOutput(null, arg);
  }

  public static String runAndGetOutput(Map<String, String> env, String... arg) {
    if (arg == null || arg.length == 0)
      return null;

    try {
      return getProcessOutput(getBuilder(env, arg).start());
    }
    catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }

  private static String getProcessOutput(Process p) throws IOException {
    final StringBuffer sb = new StringBuffer();
    final BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = null;
    while ((line = in.readLine()) != null) {
      sb.append(line).append(CHAR_LINE_BREAK);
    }

    return sb.toString();
  }

  private static ProcessBuilder getBuilder(Map<String, String> env, String... arg) {
    final ProcessBuilder builder = new ProcessBuilder();

    if (arg.length == 1)
      builder.command(arg[0]);
    else
      builder.command(arg);

    if (env != null)
      builder.environment().putAll(env);

    return builder;
  }
}